<template>
  <el-drawer
    v-model="visible"
    :title="title"
    :size="540"
    direction="rtl"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-width="labelWidth"
      :disabled="readonly"
    >
      <slot />
    </el-form>

    <template #footer>
      <div class="drawer-footer">
        <slot name="footer" />
        <div class="button-wrapper">
          <template v-if="!readonly">
            <el-button
              type="primary"
              :loading="loading"
              @click="handleSubmit"
            >
              {{ t('table.confirm') }}
            </el-button>
          </template>
          <el-button @click="visible = false">
            {{ readonly ? t('table.close') : t('table.cancel') }}
          </el-button>
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import type { FormInstance } from 'element-plus';
  import { computed, ref, watch } from 'vue';
  import { useI18n } from 'vue-i18n';

  const { t } = useI18n();

  const props = withDefaults(
    defineProps<{
      /** 是否显示 */
      modelValue?: boolean;
      /** 标题 */
      title?: string;
      /** 表单数据 */
      data?: any;
      /** 表单校验规则 */
      rules?: any;
      /** 加载状态 */
      loading?: boolean;
      /** 标签宽度 */
      labelWidth?: string;
      /** 是否只读 */
      readonly?: boolean;
    }>(),
    {
      modelValue: false,
      title: '',
      data: () => ({}),
      rules: () => ({}),
      loading: false,
      labelWidth: '120px',
      readonly: false
    }
  );

  const emit = defineEmits<{
    /** 更新显示状态 */
    (e: 'update:modelValue', value: boolean): void;
    /** 提交事件 */
    (e: 'submit', data: any): void;
    /** 关闭事件 */
    (e: 'closed'): void;
  }>();

  // 表单实例
  const formRef = ref<FormInstance>();

  // 显示状态
  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  });

  // 表单数据
  const formData = ref({ ...props.data });

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return;
    await formRef.value.validate();
    emit('submit', formData.value);
  };

  // 关闭抽屉
  const handleClosed = () => {
    if (!formRef.value) return;
    formRef.value.resetFields();
    emit('closed');
  };

  // 监听数据变化
  watch(
    () => props.data,
    (val) => {
      formData.value = { ...val };
    },
    { deep: true }
  );
</script>

<style scoped lang="scss">
  .drawer-footer {
    display: flex;
    justify-content: center;
    padding-top: 16px;
    border-top: 1px solid #eee;
    .button-wrapper {
      display: flex;
      gap: 16px;

      .el-button {
        margin: 0;
      }
    }
  }
</style>
